package com.kaishengit.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;

import com.kaishengit.pojo.User;
import com.kaishengit.util.Message;
import com.opensymphony.xwork2.ActionSupport;


public abstract class BaseAction extends ActionSupport implements SessionAware,ServletResponseAware {

	private static final long serialVersionUID = 1L;
	
	protected static final String RELOAD = "reload";
	protected static final String MAIN = "main";
	protected static final String ALL = "all";
	
	protected static final String JSON_TYPE = "application/json;charset=UTF-8";
	protected static final String TEXT_TYPE = "text/plain;charset=UTF-8";

	public static final String PDF_TYPE = "application/pdf";
	
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	
	protected Map<String,Object> session;
	
	public String execute() throws Exception {
		return list();
	}
	
	public abstract String list() throws Exception;
	public abstract String save() throws Exception;
	public abstract String delete() throws Exception;
	public abstract String input() throws Exception;
	
	
	public User getCurrentUser(){
		return (User) getSessionAttribute("currentUser");
	}
	
	public void setCurrentUser(User user){
		setSessionAttribute("currentUser",user);
	}
	
	public void setSessionAttribute(String key,Object value){
		session.put(key, value);
	}
	
	public Object getSessionAttribute(String key){
		return session.get(key);
	}
	
	public void removeSessionAttribute(String key){
		session.remove(key);
	}
	
	private void putMessage(String type,String message){
		Message msg = new Message();
		msg.setMessage(message);
		msg.setType(type);
		session.put("message", msg);
	}
	
	public void putSuccessMessage(String message){
		putMessage(Message.SUCCESS_INFO,message);
	}
	
	public void putErrorMessage(String message){
		putMessage(Message.ERROR_INFO,message);
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
	
	public void renderJson(String jsonString) throws IOException {
		response.setContentType(JSON_TYPE);
		PrintWriter out = response.getWriter();
		out.print(jsonString);
		out.flush();
		out.close();
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	
	public void setServletResponse(HttpServletResponse response) {
		this.response = response;
	}
}
